#include "tcpsubclient.h"

TCPSubClient::TCPSubClient(QObject *parent)
{
    socket = new QTcpSocket(this);

    socketStream = new QDataStream(socket);
    socketStream->setVersion(QDataStream::Qt_6_5);

    connect(this, &TCPSubClient::newMessage, this, &TCPSubClient::displayMessage);
    connect(socket, &QTcpSocket::readyRead, this, &TCPSubClient::readSocket);
    //connect(socket, &QTcpSocket::disconnected, this, &TCPClient::discardSocket);
    connect(socket, &QAbstractSocket::errorOccurred, this, &TCPSubClient::displayError);
}

TCPSubClient::~TCPSubClient()
{
    disconnect();
    discardSocket();
}

int TCPSubClient::connectToServer(QString strIP,int port){
    socket->connectToHost(QHostAddress(strIP),port);

    if(socket->waitForConnected()){
        qDebug() << ("Connected to Server");
        return 0;
    }else{
        qDebug() << QString("The following error occurred: %1.").arg(socket->errorString());
        return -1;
    }
}

void TCPSubClient::disconnect(){
    if(socket->isOpen())
        socket->close();
}

void TCPSubClient::readSocket()
{
    QByteArray buffer;
    QByteArray bytes = socket->readAll();
    QString message = QString::fromUtf8(bytes);
    //emit this->newResultMessage(message);
}

void TCPSubClient::discardSocket()
{
    socket->deleteLater();
    socket=nullptr;

    qDebug() << ("Disconnected!");
}

void TCPSubClient::displayError(QAbstractSocket::SocketError socketError)
{
    switch (socketError) {
        case QAbstractSocket::RemoteHostClosedError:
        break;
        case QAbstractSocket::HostNotFoundError:
            qDebug() << ("The host was not found. Please check the host name and port settings.");
        break;
        case QAbstractSocket::ConnectionRefusedError:
            qDebug() << ("The connection was refused by the peer. Make sure QTCPServer is running, and check that the host name and port settings are correct.");
        break;
        default:
            qDebug() << (QString("The following error occurred: %1.").arg(socket->errorString()));
        break;
    }
}

void TCPSubClient::sendMessage(QString str)
{
    if(socket)
    {
        if(socket->isOpen())
        {
            QDataStream socketStream(socket);
            socketStream.setVersion(QDataStream::Qt_5_15);

            QByteArray header;
            header.prepend(QString("fileType:message,fileName:null,fileSize:%1;").arg(str.size()).toUtf8());
            header.resize(128);

            QByteArray byteArray = str.toUtf8();
            byteArray.prepend(header);

            socketStream << byteArray;
        }
        else
            qDebug() << ("Socket doesn't seem to be opened");
    }
    else
        qDebug() << ("QTCPClient : Not connected");
}

void TCPSubClient::sendRawMessage(QString str)
{
    if (socket) {
        if (socket->isOpen()) {
            QByteArray byteArray = str.toUtf8();
            socketStream->writeRawData(byteArray, byteArray.length());
        } else
            qDebug() << ("Socket doesn't seem to be opened");
    } else
        qDebug() << ("QTCPClient : Not connected");
}

void TCPSubClient::sendAttachment(QString filePath)
{
    if(socket)
    {
        if(socket->isOpen())
        {
            if(filePath.isEmpty()){
                qDebug() << ("You haven't selected any attachment!");
                return;
            }

            QFile m_file(filePath);
            if(m_file.open(QIODevice::ReadOnly)){

                QFileInfo fileInfo(m_file.fileName());
                QString fileName(fileInfo.fileName());

                QDataStream socketStream(socket);
                socketStream.setVersion(QDataStream::Qt_5_15);

                QByteArray header;
                header.prepend(QString("fileType:attachment,fileName:%1,fileSize:%2;").arg(fileName).arg(m_file.size()).toUtf8());
                header.resize(128);

                QByteArray byteArray = m_file.readAll();
                byteArray.prepend(header);

                socketStream.setVersion(QDataStream::Qt_5_15);
                socketStream << byteArray;
            }else
                qDebug() << ("QTCPClient : Attachment is not readable!");
        }
        else
            qDebug() << ("QTCPClient : Socket doesn't seem to be opened");
    }
    else
        qDebug() << ("QTCPClient : Not connected");
}

void TCPSubClient::displayMessage(const QString& str)
{
    qDebug() << (str);
}
